#include "include.hh"

namespace asio = boost::asio;
using json = nlohmann::json;
namespace dpp = discordpp;

std::string getToken();

std::istream &safeGetline(std::istream &is, std::string &t);

int main() {
    auto bot = std::make_shared<DppBot>();
    auto aioc = std::make_shared<asio::io_context>();
    bot->debugUnhandled = true;
    bot->intents = dpp::intents::NONE | dpp::intents::GUILD_MESSAGES;
    json self;
    bot->handlers.insert(
        {"READY", [&self](json data) { std::cout << "Started!\n"; self = data["user"]; }});
    bot->prefix = "->";

    bot->respond("channelinfo", [&bot](json msg) {
        bot->getChannel()
            ->channel_id(dpp::get_snowflake(msg["channel_id"]))
            ->onRead([&bot, msg](bool error, json res) {
                bot->createMessage()
                    ->channel_id(dpp::get_snowflake(msg["channel_id"]))
                    ->content("```json\n" + res["body"].dump(4) + "\n```")
                    ->run();
            })
            ->run();
    });




    std::string token = getToken();
    bot->initBot(6, token, aioc);
    bot->run();
}


std::string getToken() {
    std::cout << "Token loading..";
    std::string token;
    std::ifstream tokenFile("token.dat");
    if (!tokenFile) {
        return "";
    }
    safeGetline(tokenFile, token);
    tokenFile.close();
    std::cout << "Returning token..";
    return token;
}

/*/
 * Source: https://stackoverflow.com/a/6089413/1526048
/*/
std::istream &safeGetline(std::istream &is, std::string &t) {
    t.clear();
    std::istream::sentry se(is, true);
    std::streambuf *sb = is.rdbuf();

    for (;;) {
        int c = sb->sbumpc();
        switch (c) {
        case '\n':
            return is;
        case '\r':
            if (sb->sgetc() == '\n') {
                sb->sbumpc();
            }
            return is;
        case std::streambuf::traits_type::eof():
            // Also handle the case when the last line has no line ending
            if (t.empty()) {
                is.setstate(std::ios::eofbit);
            }
            return is;
        default:
            t += (char)c;
        }
    }
}